#name, wid, pa
namespace :bld do
  desc "Import scan result to database"
  task :save_history_data => :environment do
    date_now =  Time.now
    pa = ENV['pa'] ? "#{BILI_PRO_PATH}#{ENV['pa']}/" : nil
    id1 = ENV['id1'] || (YAML.load(open(File.join "#{RAILS_ROOT}/config/last.yml")) rescue 0)
    id2 = ENV['id2'] || Scan.last.id
    except_ids = pa ? YAML.load(open(File.join(pa + "except.yml"))) : [-1]
    except_ids << Weekly.latest.wid unless id1.zero?
    #=====================================================================
    puts "reading scan results..."
    data = []
    WeeklyResult.stat(id1, id2, except_ids).each do |r|
      data << { :wid => r.work.wid, :name => r.work.name, :wtype => r.work.ac_type.name, :author => r.work.author_name,
                      :clicks => r.clicks, :clicks_rank => r['click_rank'],
                      :comments => r.comments, :comments_rank => r['comment_rank'],
                      :stows => r.stows, :stows_rank => r['stow_rank'],
                      :part => r.work.part_count, :score => r['point'], :score_rank => r['point_rank'],
                      :is_space_fix => (r.space_fix < 1 && r.space_fix > 0 ? true : nil)
                    }
    end
    except_ids = pa ? YAML.load(open(File.join(pa + "except.yml"))) : []
    begin
      weekly = Weekly.create! :name => ENV['name'], :wid => ENV['wid'], :last => Weekly.latest, :index => ENV['index'] || Weekly.maximum('"index"').to_i + 1
      WeeklyResult.transaction do
        puts "importing..."
        data.each{|d| WeeklyResult.create! d.merge :weekly_id => weekly.id }
      end
      WeeklyExcept.transaction do
        puts 'excepting...'
        except_ids.each{|wid| WeeklyExcept.create!(:weekly_id => weekly.id, :wid => wid) if wid > 5 && wid != Weekly.latest.wid}
      end
    rescue
      p $!,$@
    end
    File.open(%[#{RAILS_ROOT}/config/last.yml],"w"){ |io| YAML.dump id2,io }
    puts "#{Time.now - date_now} second complete"
  end
end
